import { APIDelKey, APIGenerateKey, APIKeyList, APIStartUpKey, APIStopUpKey } from "@/api/apiKey"
import debounce from "@/utils/debounce"
import { ElMessage, ElMessageBox } from "element-plus"
import { computed, nextTick, onMounted, ref } from "vue"

const PAGE_SIZE = 20
export default function useKeys() {
  const list = ref([])
  const pagination = ref({
    page: 1,
    pageSize: 0,
    count: 0
  })

  // 页数
  const pageCount = computed(() => {
    return Math.ceil(pagination.value.count / PAGE_SIZE)
  })

  // filterKey
  const filterKey = (id: number) => {
    list.value = list.value.filter((item: any) => item.id !== id)
  }
  // 更新属性
  const updateProp = (index: number, options: { key: string; value: string }) => {
    const { key, value } = options
    if (list.value[index]) {
      const startItemIndex = list.value.findIndex((item: any) => item.is_start === "2")
      if (startItemIndex > -1) {
        list.value[startItemIndex][key] = "1" as never
      }
      list.value[index][key] = value as never
    }
  }
  // 获取key列表
  const getKeys = async () => {
    const { code, data } = await APIKeyList({ page: pagination.value.page })
    if (code === 200) {
      pagination.value.count = data.count
      list.value = list.value.concat(data.list)
    }
  }
  // 删除列表
  const deleteKey = debounce(
    async (id: number) => {
      ElMessageBox.confirm("KEY将永久删除，请谨慎操作！是否继续删除？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          let { code } = await APIDelKey({ id })
          if (code === 200) {
            filterKey(id)
            ElMessage({
              type: "success",
              message: "删除成功"
            })
          }
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "删除失败"
          })
        })
    },
    500,
    true
  )

  // 启用开关
  const switchKey = debounce(
    async (id: number, is_start: string, index: number) => {
      if (is_start === "2") {
        const { code } = await APIStopUpKey(id)
        if (code === 200) {
          updateProp(index, { key: "is_start", value: "1" })
        }
      } else {
        const { code } = await APIStartUpKey(id)
        if (code === 200) {
          updateProp(index, { key: "is_start", value: "2" })
        }
      }
    },
    500,
    true
  )

  // 生成密钥
  const createKey = debounce(
    async () => {
      const { code: createCode, data: createData } = await APIGenerateKey()
      if (createCode === 200) {
        const { code: getCode, data: getData } = await APIKeyList({ page: pagination.value.page })
        if (getCode === 200) {
          const findItem = getData.list.find((item: any) => item.code_key === createData.code_key)
          if (findItem) {
            list.value.unshift(findItem as never)
          }
        }
      }
    },
    1500,
    true
  )

  // 下一页
  const nextPage = () => {
    if (pagination.value.page < pageCount.value) {
      pagination.value.page += 1
      getKeys()
    }
  }
  return { list, pagination, pageCount, getKeys, deleteKey, switchKey, createKey, nextPage }
}
